﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;

namespace FKRP.WP7.Library.Samples.Views
{
    public partial class SkeletonTracking : PhoneApplicationPage
    {
        SkeletonTracker.Client _client;

        public SkeletonTracking()
        {
            InitializeComponent();            
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!String.IsNullOrEmpty(IPAddress))
            {
                var parts = IPAddress.Split('.');
                IP4.Text = parts[0];
                IP3.Text = parts[1];
                IP2.Text = parts[2];
                IP1.Text = parts[3];

                TitlePanel.Visibility = Visibility.Collapsed;
                Settings.Visibility = Visibility.Collapsed;
                TrackerDisplay.Visibility = Visibility.Visible;
                ConnectionStatus.Text = string.Format("Not Kinected to: {0}", IPAddress);
            }
            else
                Connect.IsEnabled = false;

            base.OnNavigatedTo(e);
        }

        private int getIPAddress(TextBox txt)
        {
            int ipValue;
            if (String.IsNullOrEmpty(txt.Text))
            {
                MessageBox.Show("Please enter a valid IP Address.");
                return -1;
            }

            if (!int.TryParse(txt.Text, out ipValue))
            {
                txt.Text = string.Empty;
                MessageBox.Show("Please enter a valid IP Address.");
                return -1;
            }

            if (ipValue < 0 || ipValue > 255)
            {
                MessageBox.Show("Please enter a valid IP Address.");
                return -1;
            }

            return ipValue;
        }

        private void SaveIP_Click(object sender, RoutedEventArgs e)
        {
            var ip4 = getIPAddress(IP4);
            var ip3 = getIPAddress(IP3);
            var ip2 = getIPAddress(IP2);
            var ip1 = getIPAddress(IP1);

            if (ip1 < 0 || ip2 < 0 || ip3 < 0 || ip4 < 0)
                return;
            else
            {
                IPAddress = string.Format("{0}.{1}.{2}.{3}", ip4, ip3, ip2, ip1);
                Settings.Visibility = Visibility.Collapsed;
                TitlePanel.Visibility = Visibility.Collapsed;

                ConnectionStatus.Text = string.Format("Not Kinected to: {0}", IPAddress);
                Connect.IsEnabled = true;
            }
        }

        private String IPAddress
        {
            set
            {
                IsolatedStorageSettings.ApplicationSettings["IPADDRESS"] = value;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
            get
            {
                String ip;
                if (IsolatedStorageSettings.ApplicationSettings.TryGetValue("IPADDRESS", out ip))
                    return ip;
                else
                    return string.Empty;
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            TitlePanel.Visibility = Visibility.Visible;
            Settings.Visibility = Visibility.Visible;
            TrackerDisplay.Visibility = Visibility.Collapsed;
        }

        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            if (_client != null)
            {
                Connect.Content = "Connect to Kinect";
                _client.Dispose();
            }
            else
            {
                ConnectionStatus.Text = string.Format("Attempting to Kinect with: {0}", IPAddress);
                _client = new SkeletonTracker.Client(IPAddress, 9050);
                _client.Connect();
                _client.ReceivedTrackingData += (sndr, args) =>
                {
                    Skeleton.Children.Clear();
                    args.SkeletonData.Bones.ForEach((bone) => Skeleton.Children.Add(bone.GetLine()));
                    args.SkeletonData.Joints.ForEach((joint) => Skeleton.Children.Add(joint.GetLine()));
                };

                _client.ClientEvent += (sndr, args) => 
                {
                    if (args.IsError)
                    {
                        MessageBox.Show(args.Response);
                        //Do appropriate error handing for your application
                    }
                    else
                    {
                        switch (args.ResponseType)
                        {
                            case SkeletonTracker.ClientEventTypes.Connect:
                                ConnectionStatus.Text = string.Format("Kinected with: {0}", IPAddress);
                                Connect.Content = String.Format("Diskinect with {0}", IPAddress);
                                Connect.IsEnabled = true;
                                break;
                        }
                    }
                };
                Connect.IsEnabled = false;
            }
        }
    }
}